<template>
  <div class="node"  @dblclick="showModal($event,true)" :style="{maxWidth:(formData.customWidth?formData.customWidth:formData.maxWidth?formData.maxWidth:560)+'px'}"
       @mouseenter="showElement = true"
       @mouseleave="showElement = false"
  >
    <div class="buttons" v-if="showElement" >
      <a-tooltip class="action" >
        <template #title>
          <span>复制</span>
        </template>
        <a-button type="text" :icon="h(CloudSyncOutlined)"  @click="onCopy">
        </a-button>
      </a-tooltip>
      <a-tooltip class="action">
        <template #title>
          <span>运行</span>
        </template>
        <a-button  type="text" :icon="h(SaveOutlined)"  @click="onSave">
        </a-button>
      </a-tooltip>
    </div>
    <a-watermark :content="watermarkTitle">
      <div :class="' main-area'"  :style="config" >
        <i :style="{backgroundImage:`url(${encodeURI(formData.icon)})`}" class="node-logo"/>
        <div class="text-area" >
          <h3 v-html="toMath(formData.nodeTitle)" v-if="!!formData.nodeTitle">

          </h3>
          <div v-html="toMath(formData.nodeName)" v-if="!!formData.nodeName">

          </div>
          <div class="drawer-card" v-if="formData.complex">
            <section>
              <template v-for="(nodeType,index)  in  formData.nodeTypeList" :key="index" >
                <div v-if="formData.nodeDataMap[nodeType.value]?.length>0" class="nodeType nodeTypeFlex">
                  <img :src="encodeURI(nodeType.icon)" height="36px"  class="subNodeImg" style="margin-right: 20px">
                  <ol class="nodeType_list">
                    <li  v-html="toMath(subNode.nodeName)" v-for="(subNode,subNodeIndex) in formData.nodeDataMap[nodeType.value]" :key="subNodeIndex" class="subNode">

                    </li>
                  </ol>
                </div>
              </template>
            </section>
          </div>
        </div>
      </div>
    </a-watermark>
    <a-drawer
        :mask="false"
        v-model:open="open"
        :closable="false"
        :footer-style="{ textAlign: 'right' }"
        :width="980"
        placement="right"
        v-if="open"
        :mask-closable="false"
    >
      <template #footer>
        <a-button style="margin-right: 8px" @click="onCopy">复制</a-button>
        <a-button style="margin-right: 8px" @click="onClose">关闭</a-button>
        <a-button v-if="editFlag" type="primary" @click="onSave">保存</a-button>
      </template>
      <div v-if="editFlag">
        <div class="drawer-card">
          <h3 class="drawer-card-title">
            更改类型
          </h3>
          <a-select
              ref="select"
              style="width: 100%"
              v-model:value="formData.type"
              class="type"
              @change="handleChange"
          >
            <a-select-option v-for="(processingType,index) in processingTypeList " :value="processingType.value" :key="processingType.value">
              <div  class="custom_node">
                <i :style="{backgroundImage:`url(${encodeURI(processingType.icon)})`}" class="custom_node-logo" />
                <span class="custom_node_label">
                  {{processingType.label}}
                </span>
              </div>
            </a-select-option>
          </a-select>
        </div>
        <div class="drawer-card">
          <h3 class="drawer-card-title">
            问题内容
          </h3>
          <vditorEditor
              ref="queDrawer"
              v-model="formData.nodeName"
              class="queDrawer"/>
        </div>
        <div class="drawer-card">
          <h3 class="drawer-card-title">
            问题标题
          </h3>
          <vditorEditor
              :height="80"
              ref="queDrawer"
              v-model="formData.nodeTitle"
              class="queDrawer"/>
        </div>
        <div class="drawer-card" v-if="formData.complex">
          <section>
            <template v-for="(nodeType,index)  in  formData.nodeTypeList" :key="index" >
              <div class="nodeType">
                <a-button :icon="h(PlusOutlined)" type="primary" @click="addSubNodeData(nodeType)" class="subNodeAdd" @contextmenu="handleMutilate($event,nodeType)">
                  添加 <img :src="encodeURI(nodeType.icon)" height="100%" > [{{nodeType.label}}]
                </a-button>
              </div>
              <div v-if="formData.nodeDataMap[nodeType.value]?.length>0" class="nodeType nodeTypeFlex">
                <img :src="encodeURI(nodeType.icon)" height="48px"  class="subNodeImg" style="margin-right: 36px;margin-top: 10px">
                <div class="nodeType_list">
                  <div  v-for="(subNode,subNodeIndex) in formData.nodeDataMap[nodeType.value]" :key="subNodeIndex" class="subNode subNodeFlex">
                    <vditorEditor
                        ref="queDrawer"
                        v-model="subNode.nodeName"
                        class="queDrawer"
                        :height="120"
                    />
                    <div class="action">
                      <UpCircleOutlined @click="handleUp(nodeType.value,subNodeIndex,1)" v-if="subNodeIndex>0"/>
                      <DownCircleOutlined  @click="handleUp(nodeType.value,subNodeIndex,0)" v-if="subNodeIndex< formData.nodeDataMap[nodeType.value].length-1"/>
                      <MinusCircleOutlined @click="handleRemove(nodeType.value,subNodeIndex)"  style="color: red"/>
                    </div>

                  </div>
                </div>
              </div>
            </template>
          </section>
        </div>
      </div>
      <a-typography v-else class="drawer-card">
        <a-typography-title class="drawer-card-title">
          问题内容
        </a-typography-title>
        <a-typography-paragraph>
          <div v-html="toMath(transferText(formData.nodeName))">

          </div>
        </a-typography-paragraph>
      </a-typography>
    </a-drawer>
  </div>
  <Handle v-if="formData.inFlag" :id="props.id+'_left'"  :position="Position.Left" type="target"/>
  <Handle v-if="formData.outFlag" :id="props.id+'_right'"  :position="Position.Right" type="source"/>
  <Handle v-if="formData.upFlag" :id="props.id+'_top'"  :position="Position.Top" type="target"/>
  <Handle v-if="formData.downFlag" :id="props.id+'_bottom'" :position="Position.Bottom" type="source"/>
</template>
<script lang="ts" setup>
import {computed, ref} from 'vue';
import {Handle, Position, useVueFlow} from "@vue-flow/core";
import vditorEditor from "./vditorEditor.vue";
import useDragAndDrop from './useDnD'
import {
  PlusOutlined,
  MinusCircleOutlined,
  UpCircleOutlined,
  DownCircleOutlined,
  CloudSyncOutlined, SaveOutlined, ImportOutlined
} from '@ant-design/icons-vue';
import { h } from 'vue';
import {message} from "ant-design-vue";
const open = ref<boolean>(false);

const { toMath ,onDragStart} = useDragAndDrop()
const { updateNode } = useVueFlow()
const props = defineProps({
  id: {
    type: String,
    required: true,
  },
  data: {
    type: Object,
    required: true,
  } ,
  processingTypeList: {
    type: Array,
    required: true,
  } ,
  type: {
    type: String,
    required: true,
  }
})


let  {id,data,type:modeType} =  props


let  showElement =ref(false)

let  config =ref(JSON.parse(props.data.config))

let transferText = (data) => {
  const content = data.replaceAll('\\( ', '$')
      .replaceAll('\\(', '$')
      .replaceAll(' \\)', '$')
      .replaceAll('\\)', '$')

  return content.replace(/\\\[(.*?)\\\]/gs, '$$$$ $1 $$$$')
}


let  addSubNodeData = (data)=>{
  let nodeDataMapElement = formData.nodeDataMap[data.value];
  if (nodeDataMapElement!==undefined) {
    nodeDataMapElement.push({
      nodeType:data.value,
      icon:data.icon,
      nodeName: '',
      nodeTitle:''
    })
  }
}


let  handleMutilate = async (e,data)=>{
  e.preventDefault()
  let nodeDataMapElement = formData.nodeDataMap[data.value];
  if (nodeDataMapElement!==undefined) {
    let readText = await navigator.clipboard.readText()

    let  flag = '\n'
    if (readText.includes('------')) {
      flag = `------`
    }

    let map = readText.split(flag).filter(item=>item.trim()!=='').map(line=>{
      return {
        nodeType:data.value,
        icon:data.icon,
        nodeName: line.replaceAll('* **','**').replaceAll('  * ', '')
            .trim()
            .replace(/^- /gm, '')

            .replace(/^\d+\.\s*/gm,'')
            .trim(),
        nodeTitle:''
      }
    })

    nodeDataMapElement.push(...map);
  }

}

let  transferListToMap = (list,key,allMap,fullKey) => {
  let map = {};
  allMap.forEach(item=>{
    let itemElement = item[fullKey];
    map[itemElement] =[]
  })

  list.forEach(item => {
    let mapElement = map[item[key]];
    if (mapElement!==undefined) {
      map[item[key]].push(item)
    }
  });
  return map;
}


let  mapToList = (map) => {
  let list = [];
}

let transferListToMapData = transferListToMap(props.data.nodeDataSubList,'nodeType',props.data.nodeTypeList,'value');
let formData = reactive({
  ...props.data,
  nodeDataMap:transferListToMapData
})



let  watermarkTitle =computed(()=>{
  if (props.data.type === 'conclusion-result'){
    if (props.data.conclusionId!==null&&props.data.conclusionId !==undefined&&props.data.conclusionId !==''){
      return ''
    }else{
      return '未同步'
    }
  }else{
    return '';
  }
})

let editFlag = ref(false)

const showModal = (e,flag) => {
  e.preventDefault()
  editFlag.value = flag
  open.value = true;
};
let handleUpdate=()=> {
  updateNode(props.id, { data: formData })
}
const handleOk = (e: MouseEvent) => {
  handleUpdate()
  open.value = false;
};
const onSave = (e: MouseEvent) => {
  formData.nodeDataSubList.splice(0)
  for (const nodeDataKey in formData.nodeDataMap) {
    let nodeDataMapElement = formData.nodeDataMap[nodeDataKey];
    formData.nodeDataSubList.push(...nodeDataMapElement)
  }
  handleUpdate()
  open.value = false;
};
const onClose = (e: MouseEvent) => {
  open.value = false;
};

let  onCopy=()=>{
  let  nodeData =  `### ${formData.nodeTitle}\n${formData.nodeName}`;
  formData.nodeTypeList.forEach(item=>{
    let nodeDataMapElement = formData.nodeDataMap[item.value];
    if (nodeDataMapElement.length>0) {
      let  currentDetails = `#### ${item.label}:\n`
      nodeDataMapElement.forEach((sub,subIndex)=>{
        currentDetails+=`${subIndex+1}.${sub.nodeName}\n`
      })
      nodeData+= '\n'+currentDetails
    }

  })


  navigator.clipboard.writeText(nodeData)
  message.info('用户尝试复制內容!');
}

let  handleRemove = (key,index)=>{
  let nodeDataMapElement = formData.nodeDataMap[key];
  nodeDataMapElement.splice(index,1);
}

let handleUp = (key,index,flag)=>{
  let  arr =  formData.nodeDataMap[key];
  if (flag){
    [arr[index], arr[index-1]] = [arr[index-1], arr[index]];
  }else{
    [arr[index], arr[index+1]] = [arr[index+1], arr[index]];
  }

}
const handleChange = (e,option) => {
  let draggedType = props.processingTypeList.find(item=>item.value===option.key);
  let transferListToMapData = transferListToMap(props.data.nodeDataSubList,'nodeType',draggedType.nodeTypeList,'value');

  formData.type =  draggedType.value;
  formData.icon =  draggedType.icon;
  formData.api =  draggedType.api;
  formData.submitApi =  draggedType.submitApi;
  formData.outFlag =  draggedType.outFlag;
  formData.inFlag =  draggedType.inFlag;
  formData.config =  draggedType.customConfig;
  formData.complex =  draggedType.complex;
  formData.nodeTypeList =  draggedType.nodeTypeList;
  formData.nodeDataMap =  transferListToMapData;

  config.value =JSON.parse(formData.config)
};

let body = ref()
onMounted(() => {
  body.value = () => document.querySelector('body')
})


// 一个简单的函数来渲染 LaTeX


</script>
<style  lang="less" scoped>
.node{
  position: relative;
  width: auto;
  max-width: 560px;
  background-color: #f3f4f6;
  box-shadow: 0 0 10px #0003;
  border-radius: 2px;
  font-family: PingFangSC;
}



.main-area {
  font-family: PingFangSC;
  padding: 13px 10px 13px  30px;
  cursor:grab;
  font-size: 14px;
  line-height: 24px;
  color: #000;
  font-weight: 500;
  .text-area {
    padding-left: 10px;
    flex: 1;
  }

}

.node-logo {
  cursor:pointer;
  position: absolute;
  left: 6px;
  top:13px;
  width: 24px;
  height: 24px;
  background-repeat: no-repeat;
  background-position: center;
  background-size: 100%;
}
.queDrawer {
  border: 1px solid #e8e8e8 !important;
}
 .vue-flow__handle {
  background-color: #526d83;
   height: 24px;
   width: 12px;
  border-radius:4px
}
.vue-flow__handle[data-handlepos="top"] {
  background-color: #526d83;
  width: 24px;
  height: 12px;
  border-radius:4px
}

.vue-flow__handle[data-handlepos="bottom"] {
  background-color: #526d83;
  width: 24px;
  height: 12px;
  border-radius:4px
}

.edit {
  position: absolute;
  top: 3px;
  right: 3px;
  color: #1890ff;
}

h3 {
  font-weight: 700;
  padding-top: 20px 0;
  //color: #1890ff !important;
}

.drawer-card-title {
  //color: #1890ff !important;
  padding: 10px  0!important;
}

/deep/ .vditor-toolbar--pin {
  position: static !important;
}


.custom_node {
  font-weight:500;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  width: 100%;
  height: 100%;
  color: rgba(0, 0, 0, 65%);
  font-size: 12px;
  font-family: PingFangSC;
  &-logo {
    display: inline-block;
    width: 24px;
    height: 24px;
    background-repeat: no-repeat;
    background-position: center;
    background-size: 100%;
  }

  &-label {
    color: #000;
  }
}

/deep/ .text-area{
 h1,h2,h3,h4,h5,h6{
    font-weight: 700;
    font-size: 18px;
  }
  img{
    max-width: 100%;
  }
}
.nodeTypeFlex{
  display: flex;
}
.subNodeFlex{
  display: flex;
}
.nodeType{
  margin-top: 20px;
  .subNodeAdd{
    margin-bottom: 14px;
  }
  .nodeType_list{
    padding: 0;
    margin: 0;
    list-style: decimal!important;
    .subNode{
      padding: 0;
      margin: 15px 0 ;
      .action{
        display: flex;
        width: 52px;
        flex-wrap: wrap;
        border: 1px solid #e8e8e8;
        .anticon{
          margin-left: 12px;
          font-size: 24px;
          color: #4077ec;
        }
      }
      .queDrawer{
        //margin: 10px  0 ;
      }
      .subNodeImg{
        width: 36px;
        margin-right: 14px;
      }
    }
  }
}

.buttons{
  position: absolute;
  right: 0px;
  top:-37px;
  transition: opacity 1s ease; /* 渐变动画：透明度变化，持续0.3秒 */
  background: rgb(255 255 255 / 0.95);
  border-radius: 5px;
  padding: 2px;
  .action{
    margin:0 1px;
  }
}
</style>

